package com.eduagent.xwqeduagent.tools;

import cn.hutool.core.io.FileUtil;
import com.eduagent.xwqeduagent.constant.FileConstant;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class PDFGenerationTool {

    // 字体配置
    private static final String FONT_PATH = "src/main/resources/static/fonts/simsun.ttf";
    private static final float BODY_FONT_SIZE = 12f;
    private static final float TITLE_FONT_SIZE = 16f;
    private static final float LINE_SPACING = 1.5f;

    // 页面配置
    private static final PageSize PAGE_SIZE = PageSize.A4;
    private static final float MARGIN_TOP = 72f;    // 1 inch = 72 points
    private static final float MARGIN_BOTTOM = 72f;
    private static final float MARGIN_LEFT = 54f;
    private static final float MARGIN_RIGHT = 54f;

    @Tool(description = "Generate a PDF file with given content")
    public String generatePDF(
            @ToolParam(description = "Name of the file to save the generated PDF") String fileName,
            @ToolParam(description = "Content to be included in the PDF") String content) {

        String fileDir = FileConstant.FILE_SAVE_DIR + "/pdf";
        String filePath = fileDir + "/" + fileName;

        try {
            FileUtil.mkdir(fileDir);

            try (PdfWriter writer = new PdfWriter(filePath);
                 PdfDocument pdf = new PdfDocument(writer);
                 Document document = initDocument(pdf)) {

                // 设置文档元数据
                pdf.getDocumentInfo()
                        .setTitle(fileName)
                        .setAuthor("智能教育助手")
                        .setCreator("EduAgent System");

                // 添加标题
                addTitle(document, "智能生成文档");

                // 添加生成时间
                addTimestamp(document);

                // 处理内容段落
                processContent(document, content);

                // 添加页脚
                addFooter(document);

                return "PDF generated successfully to: " + filePath;
            }
        } catch (Exception e) {
            return "Error generating PDF: " + e.getMessage();
        }
    }

    private Document initDocument(PdfDocument pdf) {
        Document doc = new Document(pdf, PAGE_SIZE);
        doc.setMargins(MARGIN_TOP, MARGIN_RIGHT, MARGIN_BOTTOM, MARGIN_LEFT);
        return doc;
    }

    private void addTitle(Document doc, String titleText) throws IOException {
        PdfFont titleFont = loadFont(TITLE_FONT_SIZE);
        Paragraph title = new Paragraph(titleText)
                .setFont(titleFont)
                .setFontSize(TITLE_FONT_SIZE)
                .setFontColor(ColorConstants.DARK_GRAY)
                .setTextAlignment(TextAlignment.CENTER)
                .setMarginBottom(20f);
        doc.add(title);
    }

    private void addTimestamp(Document doc) throws IOException {
        String timestamp = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        Paragraph timeParagraph = new Paragraph("生成时间：" + timestamp)
                .setFont(loadFont(BODY_FONT_SIZE))
                .setFontSize(10f)
                .setFontColor(ColorConstants.GRAY)
                .setTextAlignment(TextAlignment.RIGHT)
                .setMarginBottom(15f);
        doc.add(timeParagraph);
    }

    private void processContent(Document doc, String content) throws IOException {
        PdfFont bodyFont = loadFont(BODY_FONT_SIZE);

        // 按段落分隔处理
        String[] paragraphs = content.split("\n");
        for (String para : paragraphs) {
            Paragraph p = new Paragraph(para.trim())
                    .setFont(bodyFont)
                    .setFontSize(BODY_FONT_SIZE)
                    .setFontColor(ColorConstants.BLACK)
                    .setTextAlignment(TextAlignment.JUSTIFIED)
                    .setMultipliedLeading(LINE_SPACING)
                    .setMarginBottom(12f);
            doc.add(p);
        }
    }

    private void addFooter(Document doc) throws IOException {
        PdfFont footerFont = loadFont(10f);
        Paragraph footer = new Paragraph("—— 智能教育助手生成 ——")
                .setFont(footerFont)
                .setFontColor(ColorConstants.GRAY)
                .setTextAlignment(TextAlignment.CENTER)
                .setFixedPosition(
                        doc.getLeftMargin(),
                        doc.getBottomMargin() - 20,
                        doc.getPdfDocument().getDefaultPageSize().getWidth() - doc.getLeftMargin() - doc.getRightMargin()
                );
        doc.add(footer);
    }

    private PdfFont loadFont(float fontSize) throws IOException {
        return PdfFontFactory.createFont(
                Paths.get(FONT_PATH).toAbsolutePath().toString(),
                PdfEncodings.IDENTITY_H,
                PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED
        );
    }
}